package cn.xshi.common.util;

import lombok.extern.slf4j.Slf4j;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Des
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Slf4j
public class IdCardUtil {

    /**
     * 根据身份证号计算年龄
     * @param idCard
     * @return
     */
    public static int getAgeByIdCard(String idCard){
        if(!validate(idCard)){
            throw new ExceptionUtil("身份证号不合法，无法计算年龄！");
        }
        int leh = idCard.length();
        String dates="";
        if (leh == 18) {
            int se = Integer.valueOf(idCard.substring(leh - 1)) % 2;
            dates = idCard.substring(6, 10);
            SimpleDateFormat df = new SimpleDateFormat("yyyy");
            String year=df.format(new Date());
            int u=Integer.parseInt(year)-Integer.parseInt(dates);
            return u;
        }else{
            dates = idCard.substring(6, 8);
            return Integer.parseInt(dates);
        }
    }

    /**
     * 根据身份证号计算生日
     * @param idCard
     */
    public static String getBirthDateByIdCard(String idCard){
        if(!validate(idCard)){
            throw new ExceptionUtil("身份证号不合法，无法计算生日！");
        }
        String birth = idCard.substring(6, 14);
        String birthDay = birth.substring(0, 4)+"-"+birth.substring(4, 6)+"-"+birth.substring(6, 8);
        return birthDay;
    }

    /**
     * 根据身份证号计算性别
     * @param idCard
     */
    public static String getGenderByIdCard(String idCard){
        if(!validate(idCard)){
            throw new ExceptionUtil("身份证号不合法，无法计算生性别！");
        }
        String gender = idCard.substring(16, 17);
        if(Integer.parseInt(gender)%2==0){
            gender = "女";
        }else{
            gender ="男";

        }
        return gender;
    }

    /**
     * 检查身份证是否合法
     * @param idCard
     * @return
     */
    public static boolean validate(String idCard) {
        char[] idArr = idCard.toCharArray();
        if (idArr.length != 18) {
            log.warn("身份证必须为18位！");
            return false;
        }
        // 校验因子
        int[] factors = new int[]{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        // 模除后的校验码
        String[] mods = new String[]{"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};

        // 对身份证进行加权求和计算
        int sum = 0;
        for (int i = 0; i < idArr.length - 1; i++) {
            char item = idArr[i];
            int n = item - '0';
            sum += factors[i] * n;
        }

        // 求和数据对11取模
        int mod = sum % 11;

        // 取模后的数和身份证最后以为进行对比
        String last = mods[mod];
        String lastNumber = idArr[idArr.length - 1] + "";
        if (lastNumber.equals(last)) {
            return true;
        } else {
            return false;
        }
    }
}
